package com.hex.es.component;

import com.google.common.collect.Lists;
import com.hex.es.annotation.EsBuildParamTypeInfo;
import com.hex.es.service.ParamTypeCheckInterface;
import com.hex.es.service.impl.ParamDefaultTypeCheckImpl;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * @description:
 * @author: Hex
 * @date: 2019/11/13 16:29
 */
@Component
@Slf4j
public class ParamTypeRouter implements ApplicationContextAware {

    @Resource
    private ParamDefaultTypeCheckImpl defaultTypeCheck;

    private static final List<ParamTypeCheckInterface> ROUTE_LIST = Lists.newArrayList();

    public void route(String paramName,Object object, BoolQueryBuilder boolQueryBuilder, NativeSearchQueryBuilder searchQueryBuilder, EsBuildParamTypeInfo esBuildParamTypeInfo){
        if (object == null) {
            return;
        }
        for (ParamTypeCheckInterface service : ROUTE_LIST) {
            if(service.checkType(object)){
                try {
                    service.handler(paramName,object,boolQueryBuilder,searchQueryBuilder,esBuildParamTypeInfo);
                } catch (Exception e) {
                    log.error("构建ES查询参数异常，请关注！",e);
                }
                return;
            }
        }
        try {
            defaultTypeCheck.handler(paramName,object,boolQueryBuilder,searchQueryBuilder,esBuildParamTypeInfo);
        } catch (IllegalAccessException e) {
            log.error("构建ES默认查询参数异常，请关注！",e);
        }
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String,ParamTypeCheckInterface> serviceMap = applicationContext.getBeansOfType(ParamTypeCheckInterface.class);
        serviceMap.forEach((key,value) -> {
            ROUTE_LIST.add(value);
        });
    }
}
